import JSEncrypt from 'jsencrypt';
// @ts-ignore
import CryptoJS from 'crypto-js/crypto-js';

/**
 * 公钥加密
 * @param key 公钥
 * @param content 内容
 */
export const encryptPublic = (key: string | null, content: any) => {
  const encrypt = new JSEncrypt({});
  if (key != null && content != null) {
    if (typeof content != 'string') {
      content = JSON.stringify(content);
    }
    encrypt.setPublicKey(key);
    return encrypt.encrypt(content);
  }
  return null;
};

/**
 * 私钥解密
 * @param key 私钥
 * @param content 内容
 */
export const decryptPrivate = (key: string, content: string) => {
  const decrypt = new JSEncrypt({});
  decrypt.setPrivateKey(key);
  return decrypt.decrypt(content);
};
/**
 * 私钥签名
 * @param key 私钥
 * @param content 签名内容
 */
export const signByPrivate = (key: string, content: any) => {
  const sign = new JSEncrypt();
  if (typeof content != 'string') {
    content = JSON.stringify(content);
  }
  sign.setPrivateKey(key);
  return sign.sign(content, CryptoJS.SHA1, 'sha1');
};
/**
 * 公钥验签
 * @param key 公钥
 * @param content 内容
 * @param sign 签名串
 */
export const verifyByPublic = (key: string, content: string, sign: string) => {
  const verify = new JSEncrypt();
  verify.setPublicKey(key);
  return verify.verify(content, sign, CryptoJS.SHA1);
};
